package com.lhj.xxsc.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xxsc.common.constant.AuthServerConstant;
import com.xxsc.common.utils.R;
import com.lhj.xxsc.auth.feign.MemberFeignService;
import com.lhj.xxsc.auth.util.HttpUtils;
import com.xxsc.common.vo.MemberRespVo;
import com.lhj.xxsc.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录
 *
 * @author 罗惠江
 * @version 1.0
 * @email 1511619294@qq.com
 * @date 2020/12/27 16:55
 */
@Slf4j
@Controller
@RequestMapping("/oauth2.0")
public class OAuth2Controller {

	@Autowired
	MemberFeignService memberFeignService;

	@GetMapping("weibo/success")
	public String OAuth2Login(@RequestParam("code") String code, HttpSession session) throws Exception {
		// 根据code 获取 accessToken
		System.out.println(code);
		Map<String, String> map = new HashMap<>();
		map.put("client_id", "4102584762");
		map.put("client_secret", "935bcdd290a079c84f059479e7b3e6c4");
		map.put("grant", "authorization_code");
		map.put("redirect_uri", "http://auth.xxsc.com/oauth2.0/weibo/success");
		map.put("code", code);
		HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<String, String>(), map, new HashMap<String, String>());

		//处理
		if (response.getStatusLine().getStatusCode() == 200) {
			// 获取到accessToken
			String json = EntityUtils.toString(response.getEntity());
			SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
			// 知道哪个社交账号登录
			// 如果第一次登录需要注册账号。（根据社交信息自动生成账号）
			R r = memberFeignService.oauth2login(socialUser);
			if (r.getCode().equals(0)) {
				MemberRespVo data = r.getData("memberEntity", new TypeReference<MemberRespVo>() {
				});

				System.out.println("登录成功：用户信息" + data);
				/**
				 * 1.跨域名不能共享
				 * 2.不同服务不能共享
				 * 3.不同ip不能共享
				 *
				 * 解决策略：
				 * session 复制 这个浪费空间
				 * 客户端存储 不安全，存储量不大
				 * nginx 负载均衡hash 一致性
				 *
				 * 统一存储方式 结合redis
				 *
				 *
				 */

				session.setAttribute(AuthServerConstant.LOGIN_USER, data);
				log.info("登录成功 ====> 用户信息：{" + data.toString() + "}");
				// 登录成功就返回首页
				return "redirect:http://xxsc.com";
			} else {
				return "redirect:http://auth.xxsc.com/login.html";
			}
		} else {
			return "redirect:http://auth.xxsc.com/login.html";
		}

	}
}
